package com.example.emos.wx.config.shiro;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import org.apache.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName OAuth2Filter
 * @Description TODO
 * @Author daoketa
 * @Version 1.0
 **/
@Component
@Scope("prototype")
public class OAuth2Filter extends AuthenticatingFilter {

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Autowired
    private ThreadLocalToken threadLocalToken;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${emos.jwt.cache-expire}")
    private Integer cacheExpire;

    /**
     * 拦截请求，将 token 放入令牌对象 AuthenticationToken
     * @author daoketa
     * @param servletResponse
     * @param servletRequest
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = this.getRequestToken((HttpServletRequest) servletRequest);

        if (StrUtil.isBlank(token)){
            return null;
        }

        return new OAuth2Token(token);
    }

    /**
     * 判断请求是否需要 shiro 拦截处理
     * 只放行 options 请求
     * @author daoketa
     * @param
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest req = (HttpServletRequest) request;
        // Ajax 提交 application/json 数据，会先发出 Options 请求
        // 放行 Options 请求，不需要 shiro 处理
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())){
            return true;
        }
        return false;
    }

    /**
     * 处理所有要被 shiro 处理的请求
     * @author daoketa
     * @param
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        resp.setHeader("Content-Type", "text/html;charset=UTF-8");
        //允许跨域请求
        resp.setHeader("Access-Control-Allow-Credentials", "true");
        resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));

        threadLocalToken.clear();
        /** 获取请求中的 token ，如果 token 不存在，直接返回 401 */
        String token = this.getRequestToken(req);
        if (StrUtil.isBlank(token)){
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("令牌不存在!");
            return false;
        }

        try {
            /** 查看 token 是否失效 */
            jwtTokenUtils.verifierToken(token);
        }catch (TokenExpiredException e){
            /** 查看 redis 的 token 是否失效 */
            if (redisTemplate.hasKey(token)){
                redisTemplate.delete(token);
                Integer userId = jwtTokenUtils.getUserId(token);
                token = jwtTokenUtils.createToken(userId);
                redisTemplate.opsForValue().set(token, userId + "", cacheExpire, TimeUnit.DAYS);
                threadLocalToken.setToken(token);
            }else {
                resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
                resp.getWriter().print("令牌已过期!");
                return false;
            }
        }catch (Exception e){
            resp.setStatus(HttpStatus.SC_UNAUTHORIZED);
            resp.getWriter().print("令牌无效!");
            return false;
        }

        boolean bool = executeLogin(servletRequest, servletResponse);

        return bool;
    }

    /**
     * 获取请求头中的 token
     * @author daoketa
     * @param request
     */
    public String getRequestToken(HttpServletRequest request){
        // 从请求头中获取 token
        String token = request.getHeader("token");

        // 请求头无 token，则从请求参数中获取
        if (StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }

        return token;
    }

    @Override
    public void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        super.doFilterInternal(request, response, chain);
    }

}
